import axios from 'axios'
import { Notification, Message } from 'element-ui'
import { getToken, removeToken } from '@/util/auth'
import router from '@/router'

// 'Content-Type': 'multipart/form-data'

// 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_AJS_USER,
  // 超时
  timeout: 10000,
  withCredentials: true
})
// 请求拦截器
service.interceptors.request.use(
  config => {
    const ContentType = config.headers['Content-Type']
    if (ContentType && ContentType === 'multipart/form-data') {
      config.timeout = 0
    }
    if (router.options._hmt) {
      router.options._hmt.push(['_trackPageview', config.url])
    }
    if (getToken()) {
      config.headers.Authorization = 'Basic_' + getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// code白名单
const codeWhiteList = [20]

// 响应拦截器
service.interceptors.response.use(res => {
  const status = res.data.status
  if (status === 401 || status === 403) {
    removeToken()
    router.push({
      path: '/login',
      query: {
        redirect: router.currentRoute.fullPath
      }
    })
  } else if (status === 203) {
    Notification.error({
      title: res.data.data,
      message: res.data.message
    })
  } else if (status !== 200) {
    if (res.config.responseType === 'blob') {
      return res.data
    }
    if (codeWhiteList.indexOf(res.data.code) === -1) {
      Notification.error({
        title: '系统提示',
        message: '操作失败，请稍后再试'
      })
    }
    return Promise.reject(res.data)
  } else {
    return res.data
  }
},
error => {
  Message({
    message: '服务器开了小差，请稍后再试试哟',
    // message: error.message,
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error)
}
)

export default service
